package com.kye.express.business.help.list;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.databinding.FragmentHelpBinding;
import com.kye.express.utils.NetUtils;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.help.ResultGetHelpListBean;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 帮助 Presenter
 * <p>
 * Created by SkyYu on 2018/01/9
 */
public class HelpFragment extends BaseAppCompatFragment implements HelpFragmentContract.HelpFragmentView {

    private final static String TAG_TYPE = "TAG_TYPE";
    private FragmentHelpBinding mBinding;
    private MultiTypeAdapter mAdapter;
    private HelpFragmentContract.HelpFragmentPresenter mPresenter;
    private HelpItemTypeModel type;

    public static HelpFragment newInstance(HelpItemTypeModel helpItemTypeModel) {
        Bundle args = new Bundle();
        args.putSerializable(TAG_TYPE, helpItemTypeModel);
        HelpFragment fragment = new HelpFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            type = (HelpItemTypeModel) getArguments().getSerializable(TAG_TYPE);
        } else {
            type = (HelpItemTypeModel) savedInstanceState.getSerializable(TAG_TYPE);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_help, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view, savedInstanceState);
        initData();
        initEvent();
    }
    @Override
    public void onDestroyView() {
        if (mPresenter != null) mPresenter.unbind();
        super.onDestroyView();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        mPresenter.onSaveInstanceState(outState);
        outState.putSerializable(TAG_TYPE, type);
        super.onSaveInstanceState(outState);
    }

    private void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initBinding(view);
        initPresenter(savedInstanceState);
    }

    private void initData() {
        initAdapter();
    }

    private void initEvent() {
        mBinding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                if(NetUtils.isNetworkAvailable(getActivity())){
                    mPresenter.refreshInit(type.getClassId());
                }else{
                    ToastManager.show(getActivity(),getString(R.string.common_net_error));
                }
            }
        });
        mBinding.refreshLayoutHelp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if(NetUtils.isNetworkAvailable(getActivity())){
                    mPresenter.refresh(type.getClassId());
                }else{
                    ToastManager.show(getActivity(),getString(R.string.common_net_error));
                }
            }
        });
        RxView.clicks(mBinding.llErrorServerCustom.btErrorServerRetry)
                .compose(this.bindToLifecycle())
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {

                    }
                });
        RxView.clicks(mBinding.llEmptyCustom.btEmptyRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    Logger.d("HelpFragment - initEvent - EmptyRetry");
                    mBinding.statusLayout.showLoadingView();
                });
        RxView.clicks(mBinding.llErrorNetCustom.btErrorNetRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    Logger.d("HelpFragment - initEvent - ErrorNetRetry");
                    mBinding.statusLayout.showLoadingView();
                });
        RxView.clicks(mBinding.llErrorServerCustom.btErrorServerRetry)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    Logger.d("HelpFragment - initEvent - ErrorServerRetry");
                    mBinding.statusLayout.showLoadingView();
                });
    }

    private void initBinding(View view) {
        mBinding = DataBindingUtil.bind(view);
    }

    private void initPresenter(@Nullable Bundle savedInstanceState) {
        mPresenter = new HelpFragmentContract.HelpFragmentPresenter();
        mPresenter.bind(this);
        mPresenter.onCreate(savedInstanceState);
    }

    private void initAdapter() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(ResultGetHelpListBean.class, new HelpItemViewBinder(getActivity()));
        mBinding.recyclerHelp.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBinding.recyclerHelp.setAdapter(mAdapter);
    }

    @Override
    protected void initDataFirstTime(boolean isForceUpdate, @Nullable Bundle savedInstanceState) {
        super.initDataFirstTime(isForceUpdate, savedInstanceState);
        mBinding.statusLayout.showLoadingView();
    }

    @Override
    public void refreshInitSuccess(List<ResultGetHelpListBean> bean) {
        mBinding.statusLayout.showContentView();
        mAdapter.setItems(bean);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void refreshInitApiError(OpenApiResult<List<ResultGetHelpListBean>> result, int code, String msg) {
        mBinding.statusLayout.showErrorServerView();
        ToastManager.show(getActivity(), msg);
        Logger.d("HelpFragment - refreshInitApiError - result:" + result + ",code:" + code + ",msg:" + msg);
    }

    @Override
    public void refreshInitOtherError(Throwable e) {
        mBinding.statusLayout.showErrorNetworkView();
        ToastManager.show(getActivity(), getString(R.string.common_net_error));
        Logger.d("HelpFragment - refreshInitOtherError : " + e.getMessage());
        e.printStackTrace();
    }

    @Override
    public void refreshSuccess(List<ResultGetHelpListBean> bean) {
        mBinding.refreshLayoutHelp.finishRefresh(true);
        mAdapter.setItems(bean);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void refreshApiError(OpenApiResult<List<ResultGetHelpListBean>> result, int code, String msg) {
        mBinding.refreshLayoutHelp.finishRefresh(true);
        mBinding.statusLayout.showErrorServerView();
        ToastManager.show(getActivity(), msg);
        Logger.d("HelpFragment - refreshApiError - result:" + result + ",code:" + code + ",msg:" + msg);
    }

    @Override
    public void refreshOtherError(Throwable e) {
        mBinding.refreshLayoutHelp.finishRefresh(true);
        ToastManager.show(getActivity(), getString(R.string.common_net_error));
        Logger.d("HelpFragment - refreshOtherError : " + e.getMessage());
        e.printStackTrace();
    }

    @Override
    public FragmentHelpBinding getBinding() {
        return mBinding;
    }

    @Override
    public HelpItemTypeModel getType() {
        return type;
    }
}